package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.RetrofitService.CommodityBrand
import com.abc.robot01.retrofit.bean.DataB
import com.abc.robot01.retrofit.bean.FetchDataRequest2
import com.abc.robot01.retrofit.bean.HouseType
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class ShangPinKuViewModel : BaseViewModel() {

    val TAG = "ShangPinKuViewmodel"

    val showPopup =  mutableStateOf(false)

    val selected2 = mutableStateOf("全部")
    val selected3 =  mutableStateOf("全部")
    // MutableStateFlow 用来保存当前的列表状态
    private val _questionList = MutableStateFlow<List<DataB>>(emptyList())
    val dataList: StateFlow<List<DataB>> = _questionList

    val name = mutableStateOf("")

    var isToggled = mutableStateOf(true)

    //系列
    private val _question2List = MutableStateFlow<List<CommodityBrand>>(emptyList())
    val question2List: StateFlow<List<CommodityBrand>> = _question2List

    //品牌
    private val _question3List = MutableStateFlow<List<CommodityBrand>>(emptyList())
    val question3List: StateFlow<List<CommodityBrand>> = _question3List

    //品牌List
    val brandList = mutableStateListOf<ButtonState>()

    val interestsCode = mutableStateOf("")
    val interests = mutableStateOf("全部")

//    val brand = mutableStateOf("")

//    val series = mutableStateOf("")

    //系列List
    val seriesList = mutableStateListOf<ButtonState>()

    // 模拟网络分批返回数据的函数

    val pageSize = 100;

    fun  reset(){
        repeat(seriesList.size){
            seriesList[it]= seriesList[it].copy(isSelected = false)
        }
        repeat(brandList.size){
            brandList[it]= brandList[it].copy(isSelected = false)
        }
    }

    //默认价格降序
    fun loadMoreData(
        orderBy: String = if (isToggled.value) "price asc" else "price desc",
        name: String = "",
        interest: String = interestsCode.value,
        brand2: String = brandList.filter { it.isSelected }.joinToString(separator = ",") { it.code },
        series2: String = seriesList.filter { it.isSelected }.joinToString(separator = ",") { it.code },
    ) {
        viewModelScope.launch(IO) {
            try {
            Log.e(TAG, "start loadMoreData,name:$name");
            Log.e(TAG, "商品库,名称:$name,喜欢:" + interest);
            _questionList.value = emptyList()
            repeat(10000) {
                val newBatch = fetchNextBatchFromNetwork(
                    name,
                    offset = pageSize * it,
                    fetchSize = pageSize,
                    orderBy = orderBy,
                    interest = interest,
                    brand= brand2,
                    series=series2,
                )
                if (newBatch.first.isEmpty()) return@launch
                _questionList.value += newBatch.first
                if (newBatch.second == _questionList.value.size) {
                    Log.e(TAG, "last data ,total  ${newBatch.second}");
                    return@launch
                }
            }
        } catch (e:Exception){
            e.printStackTrace();
                showToast(e.message!!);
        }
        }
    }

    // 模拟获取网络数据的方法
    private suspend fun fetchNextBatchFromNetwork(
        name: String,
        interest: String,
        offset: Int,
        fetchSize: Int,
        orderBy: String,
        brand: String,
        series: String,
    ): Pair<List<DataB>, Int> {
        val data = mutableListOf<DataB>()
        val result = RetrofitService.instance.getCompanyProduct(
            accessToken=Robot.accessToken,
            userId = Robot.userId, companyId = Robot.companyId,
            FetchDataRequest2(
                offset = offset,
                fetchSize = fetchSize,
                orderBy = orderBy,
                name = name,
                interest = interest,
                brand = brand,
                series = series,
            )
        )
//        Log.e(TAG, "userId ${Robot.userId}");
//        Log.e(TAG, "companyId ${Robot.companyId}");
//        Log.e(TAG, "fetchNextBatchFromNetwork: $result");
        if (result.code == 200) {
            result.data.list.forEach {
//                Log.e(TAG, "commodity item : ${it}");
                data.add(
                    DataB(
                        unitName=it.unitName,
                        id = it.id,
                        name = it.name,
                        price = "${it.price}",
                        thumbnail = it.thumbnail
                    )
                )
            }
        }
//        Log.e(TAG, "fetchNextBatchFromNetwork, data.size: ${data.size}");
        // 返回一些新数据
        return data to result.data.total
    }

    init {
        loadMoreData()
        loadData2()
    }

    private fun loadData2() {
        //喜好
        viewModelScope.launch {
            try {
                val s2 = RetrofitService.instance.getLabelList(
                    accessToken = Robot.accessToken,
                    companyId = Robot.companyId,
                    type = "COMMODITY_BRAND"
                )
                s2.data.forEach {
                    Log.e(TAG, "商品品牌:${it.name}")
                }
                _question3List.value = s2.data
                Log.e(TAG, "商品品牌:$s2")

                s2.data.forEach {
                    brandList.add(ButtonState(it.name, it.id, false))
                }

                Log.e(TAG, "系列")

                val s3 = RetrofitService.instance.getLabelList(
                    accessToken = Robot.accessToken,
                    companyId = Robot.companyId,
                    type = "COMMODITY_SERIES"
                )
                s3.data.forEach {
                    Log.e(TAG, "商品系列:${it.name}")
                }
                _question2List.value = s3.data

                s3.data.forEach {
                    seriesList.add(ButtonState(it.name, it.id, false))
                }

                Log.e(TAG, "商品系列:$s3")

            } catch (e:Exception){
                e.printStackTrace();
                showToast(e.message!!)
            }


        }
    }
}


